package com.bitcola.security.activity.biz;


import com.bitcola.security.activity.mapper.BalanceChangeLogMapper;
import com.bitcola.security.activity.mapper.ColaUserBalanceMapper;
import com.bitcola.security.auth.common.util.EncoderUtil;
import com.bitcola.security.common.constant.BalanceTypeConstants;
import com.bitcola.security.common.constant.FinancialConstant;
import com.bitcola.security.common.exception.LackBalanceException;
import com.bitcola.security.common.util.Snowflake;
import com.bitcola.entity.BalanceChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class TransformBiz {

    @Autowired
    BalanceChangeLogMapper balanceChangeLogMapper;
    @Autowired
    ColaUserBalanceMapper colaUserBalanceMapper;

    Snowflake snowflake=new Snowflake(4,11);

    @Transactional
    public void transfrom(String userId, BigDecimal amount  ,String coinCode,String balanceType){

        int index=0;
        Date now=new Date();

        var balanceChangeApply=new BalanceChange();
        balanceChangeApply.setId(snowflake.nextIdStr());
        balanceChangeApply.setUserId(userId);
        balanceChangeApply.setType(FinancialConstant.TRANSFORM_OUT);
        balanceChangeApply.setAmount(amount.negate());
        balanceChangeApply.setCreateTime(now);
        balanceChangeApply.setSource(balanceType);
        balanceChangeApply.setCoinCode(coinCode);
        var balanceChangeBalance=new BalanceChange();
        balanceChangeBalance.setId(snowflake.nextIdStr());
        balanceChangeBalance.setUserId(userId);
        balanceChangeBalance.setType(FinancialConstant.TRANSFORM_IN);
        balanceChangeBalance.setAmount(amount);
        balanceChangeBalance.setCreateTime(now);
        balanceChangeBalance.setCoinCode(coinCode);
        balanceChangeBalance.setSource(BalanceTypeConstants.BALANCE);

        balanceChangeLogMapper.insert(balanceChangeApply);
        balanceChangeLogMapper.insert(balanceChangeBalance);


        if(balanceType.equals(BalanceTypeConstants.MINING)){
            index = colaUserBalanceMapper.changeUserBanlance(userId, coinCode, amount, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, amount.negate(), EncoderUtil.BALANCE_KEY);

        }else {
            index = colaUserBalanceMapper.changeUserBanlance(userId, coinCode, amount, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, amount.negate(), BigDecimal.ZERO, EncoderUtil.BALANCE_KEY);
        }
         if(index==0) throw new LackBalanceException("");





    }

}
